import { Stomp } from "./stomp"

class WebSocketClient {
	/**
	 * @param url  ws地址
	 * @param  event 监听事件
	 */
  constructor(url, event) {
    this.socketOpen = false;
    this.socketMsgQueue = [];
    this.baseURL = url || 'ws://web:web@172.16.10.58:50286/ws';
    this.event = event || '';
    this.header = {
      login: 'web',
      passcode: 'web'
    };
    this.SocketTask = null;
    this.client = null;
  }

  webSocketInit(url, event) {
    if (url) this.baseURL = url;
    if (event) this.event = event;
	
    console.log('🔄 开始连接WebSocket...');
    this.SocketTask = uni.connectSocket({
      url: this.baseURL,
      multiple: true,
      complete: () => {}
    });

    // 直接在这里设置事件，不要调用onWebSocketEvent
    this.setupWebSocketEvents();
  }

  // 新增：设置WebSocket事件的方法
  setupWebSocketEvents() {
    const ws = {
      send: this.sendMessage.bind(this),
      onopen: null,
      onmessage: null,
      close: this.closeSocket.bind(this)
    };

    this.SocketTask.onOpen((res) => {
      console.log('WebSocket连接已打开！', res);
      this.socketOpen = true;
      
      // 直接创建STOMP客户端，不要延迟
      console.log('🔄 开始创建STOMP客户端...');
      
      try {
        this.client = Stomp.over(ws);
        console.log('STOMP客户端创建完成:', this.client);
        
        // 检查STOMP客户端方法
        console.log('🔍 STOMP方法检查:', {
          connect: typeof this.client.connect,
          disconnect: typeof this.client.disconnect,
          subscribe: typeof this.client.subscribe
        });
        
        // 立即连接 - 添加更多调试信息
        console.log('🚀 准备调用STOMP connect...');
        console.log('this.client:', this.client);
        console.log('this.client.connect:', this.client.connect);
        
        // 确保connect方法存在
        if (typeof this.client.connect === 'function') {
          console.log('✅ connect方法存在，开始调用...');
          
          // 定义回调函数
          const onConnect = () => {
            console.log('✅ STOMP连接成功！');
            console.log('连接状态:', this.client.connected);
            uni.$emit(this.event, this.client);
          };
          
          const onError = (error) => {
            console.error('❌ STOMP连接失败:', error);
            console.error('错误详情:', error);
          };
          
          console.log('回调函数定义完成:', {
            onConnect: typeof onConnect,
            onError: typeof onError
          });
          
          // 修复：正确调用STOMP connect
          console.log('🔄 调用this.client.connect...');
          
          try {
            // 调用connect
            const result = this.client.connect({}, onConnect, onError);
            console.log('connect调用结果:', result);
            
            // 如果返回的是函数，尝试调用它
            if (typeof result === 'function') {
              console.log('🔄 connect返回函数，尝试调用...');
              result();
            }
            
          } catch (e) {
            console.error('调用connect失败:', e);
          }
          
          console.log('✅ STOMP connect调用完成');
          
          // 检查连接状态
          setTimeout(() => {
            console.log('🔍 延迟检查STOMP状态:', {
              connected: this.client.connected,
              ws: !!this.client.ws,
              readyState: this.client.ws?.readyState
            });
          }, 1000);
          
        } else {
          console.error('❌ connect方法不存在！');
          console.error('this.client类型:', typeof this.client);
          console.error('this.client内容:', this.client);
        }
        
      } catch (error) {
        console.error('💥 创建或连接STOMP时出错:', error);
        console.error('错误堆栈:', error.stack);
      }
    });

    this.SocketTask.onMessage((res) => {
      console.log('📨 收到WebSocket消息:', res);
      
      // 修复：正确提取消息数据
      let messageData = res.data;
      if (res.message) {
        messageData = res.message; // 使用res.message而不是res.data
      }
      
      console.log(' 提取的消息数据:', messageData);
      
      // 检查是否是STOMP响应
      if (messageData && typeof messageData === 'string') {
        // 处理空消息（心跳包）
        if (messageData.trim() === '') {
          console.log('💓 收到心跳包，忽略');
          return;
        }
        
        console.log('🔍 分析STOMP消息:', messageData);
        
        if (messageData.includes('CONNECTED')) {
          console.log('✅ 收到STOMP CONNECTED响应！');
          
          // 手动设置连接状态
          if (this.client) {
            this.client.connected = true;
            console.log('手动设置STOMP连接状态为true');
            
            // 触发连接成功事件
            console.log('🚀 触发STOMP连接成功事件');
            uni.$emit(this.event, this.client);
          }
          
        } else if (messageData.includes('ERROR')) {
          console.log('❌ 收到STOMP ERROR响应！');
          
          // 解析错误信息
          if (messageData.includes('Session closed')) {
            console.log('⚠️ 检测到会话关闭，可能是正常断开');
          }
          
        } else if (messageData.includes('MESSAGE')) {
          console.log(' 收到STOMP MESSAGE响应！');
          
          // 关键：让STOMP库处理MESSAGE帧
          this.handleStompMessage(messageData);
          
        } else if (messageData.includes('RECEIPT')) {
          console.log('✅ 收到STOMP RECEIPT响应！');
          
        } else {
          console.log('⚠️ 未知的STOMP消息类型');
        }
      }
      
      // 关键修复：确保消息传递给STOMP库
      if (ws.onmessage) {
        console.log('🔄 调用ws.onmessage传递给STOMP库');
        try {
          ws.onmessage(res);
        } catch (error) {
          console.error('❌ ws.onmessage调用失败:', error);
        }
      } else {
        console.log('⚠️ ws.onmessage不存在');
      }
    });

    this.SocketTask.onError((res) => {
      console.log('❌ WebSocket错误:', res);
      this.socketOpen = false;
    });

    this.SocketTask.onClose((res) => {
      this.socketOpen = false;
      console.log('🔌 WebSocket已关闭:', res);
    });
  }

  // 新增：处理STOMP消息的方法
  handleStompMessage(messageData) {
    console.log(' 开始处理STOMP MESSAGE帧...');
    
    try {
      // 解析STOMP消息帧
      const lines = messageData.split('\n');
      const headers = {};
      let body = '';
      let inBody = false;
      
      for (let i = 0; i < lines.length; i++) {
        const line = lines[i];
        
        if (line === '') {
          inBody = true;
          continue;
        }
        
        if (inBody) {
          body += line;
        } else if (line.includes(':')) {
          const [key, value] = line.split(':', 2);
          headers[key.trim()] = value.trim();
        }
      }
      
      console.log(' MESSAGE帧解析结果:', {
        headers: headers,
        body: body,
        destination: headers.destination,
        contentType: headers['content-type'],
        messageId: headers['message-id']
      });
      
      // 检查是否是聊天消息
      if (headers.destination && 
          headers.destination.includes('/friend/') && 
          headers['content-type'] === 'text/plain;charset=UTF-8') {
        
        console.log('✅ 识别为聊天消息');
        
        try {
          const messageData = JSON.parse(body);
          console.log(' 解析的聊天消息:', messageData);
          
          // 触发聊天消息事件
          uni.$emit('chatMessage', {
            data: messageData,
            headers: headers,
            rawMessage: messageData
          });
          
        } catch (parseError) {
          console.error('❌ 解析聊天消息JSON失败:', parseError);
          console.error('原始消息体:', body);
        }
      }
      
      // 关键：直接调用STOMP库的消息处理
      if (this.client && this.client.ws && this.client.ws.onmessage) {
        console.log('🔄 直接调用STOMP库的onmessage');
        try {
          // 创建标准的事件对象
          const event = {
            data: messageData,
            type: 'message'
          };
          
          this.client.ws.onmessage(event);
          console.log('✅ STOMP库onmessage调用成功');
          
        } catch (error) {
          console.error('❌ STOMP库onmessage调用失败:', error);
        }
      } else {
        console.log('⚠️ STOMP库onmessage不可用');
      }
      
    } catch (error) {
      console.error(' 处理STOMP MESSAGE帧失败:', error);
      console.error('原始消息:', messageData);
    }
  }

  disconnect() {
    this.SocketTask.close();
  }

  sendMessage(message) {
    if (this.socketOpen) {
      this.SocketTask.send({
        data: message
      });
    } else {
      this.socketMsgQueue.push(message);
    }
  }

  closeSocket() {
    console.log('closeSocket');
  }
}

export default WebSocketClient;
